package com.example.mq.mqserver;

import com.example.mq.common.*;
import com.example.mq.mqserver.core.BasicProperties;
import com.example.mq.mqserver.core.Consumer;
import com.example.mq.mqserver.core.Exchange;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 本质上就是一个TCP服务器
 */
@Slf4j
public class BrokerServer {
    private ServerSocket serverSocket = null;
    //当前考虑一个BrokerServer上只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");

    //使用这个哈希表 表示当前所有的会话
    //此处的key是channelId value为对应的socket对象
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    private ExecutorService executorService = null;
    //引入一个boolean变量 控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        log.info("brokerServer 启动!");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                //把处理连接的逻辑丢给这个线程池
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        }catch (SocketException e){
            log.info("服务器停止运行");
        }

    }

    //停止服务器
    public void stop() throws IOException {
        runnable = false;
        //把线程池中的任务都放弃了 让线程都销毁
        executorService.shutdown();
        serverSocket.close();
    }


    //通过这个方法 来处理一个客户端的连接
    //在这一个方法中 可能会涉及到多个请求和响应
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            //需要按照特定格式解析 使用DataInputStream和DataOutputStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3.把响应写回客户端
                    writeResponse(dataOutputStream, response);
                }
            } catch (EOFException e) {
                //对于这个代码  如果DataInputStream 如果读到EOF 就会抛出一个eofException异常
                //需要借助这个异常来结束循环
                log.info("connection关闭! 客户端的地址: {} : {}", clientSocket.getInetAddress().toString(), clientSocket.getPort());
            }
        } catch (ClassNotFoundException | MqException | IOException e) {
            log.info("connection 出现异常");
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                //一个tcp连接中 可能包含多个channel 需要把这个socket对应的所有channel也顺便清理掉
                clearCloseSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //遍历上述sessions哈希表 把被关闭的socket对应的键值对删除
    private void clearCloseSession(Socket clientSocket) {
        List<String> toDeleteChannelId = new ArrayList<>();
        for(Map.Entry<String,Socket> entry : sessions.entrySet()){
            if(entry.getValue() == clientSocket){
                //不能一边遍历一边删除 此时影响结构影响遍历
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId){
            sessions.remove(channelId);
        }
        log.info("清理session完成 被清理的sessionId :{}",toDeleteChannelId);
    }

    //处理一次请求 返回一次响应
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        //先对request中的payload做一个初步的解析
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        log.info("rid:{} , channelId:{} , type:{}, length:{}", basicArguments.getRid(), basicArguments.getChannelId(),
                request.getType(), request.getLength());
        //根据type的值 来进一步区分接下来这次请求要干什么
        boolean ok = true;
        if (request.getType() == 0x1) {
            //创建channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            log.info("创建channel完成 channelId:{}", basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            //销毁channel
            sessions.remove(basicArguments.getChannelId());
            log.info("销毁channel完成 channelId:{}", basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            //创建交换机 此时payload是ExchangeDeclareArguments 对象了
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            //删除交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            //创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            //删除队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            //创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(),
                    arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            //删除绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            //发布消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            //订阅消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        //这个回调函数要做的工作 就是把服务器收到的消息可以直接推送到对应的消费者客户端
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            //先知道当前收到的消息要发给那个客户端
                            //此处consumerTag 其实是channelId 根据channelId去sessions中查询 就可以得到相应的socket\对象 就可以发送数据
                            //1.根据channelId找到 socket对象
                            Socket clientSocket = sessions.get(consumerTag);
                            if (clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokeServer] 订阅消息的客户端已经关闭");
                            }
                            //构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setChannelId(consumerTag);
                            subScribeReturns.setRid("");//这里只有响应 没有请求 不需要rid
                            subScribeReturns.setOk(true);
                            subScribeReturns.setConsumerTag(consumerTag);
                            subScribeReturns.setBasicProperties(basicProperties);
                            subScribeReturns.setBody(body);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);
                            Response response = new Response();
                            //0xc表示服务器给消费者客户端推送的消息数据
                            response.setType(0xc);
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            //把数据写回 给客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            //调用basicAck确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        } else {
            //当前type是非法的
            throw new MqException("[BrokerServer] 未知的 type type:" + request.getType());
        }
        //构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        log.info("rid:{} , channelId:{}, type:{}, length:{}", basicReturns.getRid(), basicReturns.getChannelId(),
                response.getType(), response.getLength());
        return response;
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        //刷新缓冲区
        dataOutputStream.flush();
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求格式出错");
        }
        request.setPayload(payload);
        return request;
    }
}
